# coding: utf-8
from datetime import datetime
from typing import List

from sqlalchemy import Integer, String, Column, DateTime
from sqlalchemy.orm import Session

from .base import check_session, BaseModel


class HistoryDownloadTableModel(BaseModel):
    __tablename__ = 'history_download'
    id = Column(Integer, autoincrement=True, primary_key=True)
    url = Column(String(255), nullable=False)
    save_path = Column(String(255), nullable=False)
    create_time = Column(DateTime, default=datetime.now, nullable=False)


# @check_session
def history_download_exist(url: str, session: Session = None):
    result = session.query(HistoryDownloadTableModel).filter(HistoryDownloadTableModel.url == url).first()
    if result:
        return True
    else:
        return False


# @check_session
def add_history_download(url: str, save_path: str, session: Session = None):
    if history_download_exist(url, session):
        return
    model = HistoryDownloadTableModel(url=url, save_path=save_path)
    session.add(model)
    session.commit()


# @check_session
def history_download_list(session: Session = None) -> List[HistoryDownloadTableModel]:
    result = session.query(HistoryDownloadTableModel).all()
    return result


# @check_session
def history_download_delete(id: int, session: Session = None):
    session.query(HistoryDownloadTableModel).filter(HistoryDownloadTableModel.id == id).delete()
    session.commit()


def clear_history_download(session: Session = None):
    session.query(HistoryDownloadTableModel).delete()
    session.commit()
